import { defineStore } from "pinia";
import { ref, reactive, watch, computed, nextTick } from 'vue'
import { CartApi } from "@/api";
export default defineStore('cart', () => {
    const listMain = ref<Vm.Cart[]>([])
    //list列表的属性
    const listChecked = ref<Status.listChecked[]>([])
    const isInit = ref<boolean>(false)
    const total = ref<number>()
    const init = async () => {
        if (!sessionStorage.getItem('token')) return
        if (isInit.value) return
        isInit.value = true
        listMain.value = await CartApi.getlist()
        listChecked.value = listMain.value.reduce((list: Status.listChecked[], item: Vm.Cart): Status.listChecked[] => {
            list.push({ id: item.id, checked: true, editChecked: false })
            return list
        }, [])
    }


    const removeIds = computed((): number[] => {
        return listChecked.value.reduce((ids: number[], item: Status.listChecked) => {
            if (item.editChecked) ids.push(item.id)
            return ids
        }, [])
    })
    const submitIds = computed((): number[] => {
        return listChecked.value.reduce((ids: number[], item: Status.listChecked) => {
            if (item.checked) ids.push(item.id)
            return ids
        }, [])
    })

    const remove = async () => {
        await CartApi.remove({ ids: removeIds.value })
        removeIds.value.forEach((id: number) => {
            listMain.value.splice(listMain.value.findIndex((item: Vm.Cart) => item.id === id), 1)
            listChecked.value.splice(listChecked.value.findIndex((item: Status.listChecked) => item.id === id), 1)
        })
    }
    watch(listMain, async () => {
        total.value = await CartApi.gettotal(sessionStorage.getItem('name') as string)
    }, { deep: true })

    const Subtotal = computed((): number => {
        return listMain.value.reduce((Subtotal: number, item: Vm.Cart) => {
            //如果item的listChecked在ids里面
            const i = listChecked.value.findIndex(item2 => item2.id === item.id)
            if (listChecked.value[i].checked) {
                Subtotal += item.count * item.price
            }
            return Subtotal
        }, 0)
    })
    return { listMain, init, listChecked, removeIds, isInit, remove, total, Subtotal, submitIds }
}, {
    persist: {
        enabled: true
    }
})
